package com.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

@Controller
public class RequestController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        request.setAttribute("zjb", "张锦波");
        request.getSession().setAttribute("website", "https://www.baidu.com/");
        return "forward:/ok";
    }

    @RequestMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "zjb", required = false) String name,
                     @SessionAttribute(value = "website", required = false) String session,
                     HttpServletRequest request) {
        //获取request域中的数据
        System.out.println("---------获取request域中的数据----------");
        System.out.println("name=" + name);
        System.out.println("通过servlet-api-获取name=" + request.getAttribute("zjb"));
        //获取session域中的数据
        System.out.println("---------获取session域中的数据----------");
        System.out.println("website=" + session);
        System.out.println("通过servlet-api-获取website=" + request.getSession().getAttribute("website"));
        return "success";
    }
    //响应一个注册请求
    @GetMapping("/register")
    public String register(Map<String, Object> map,
                           Model model,
                           HttpServletResponse response){
        //注册请求会将数据封装到map和model中
        //map中的数据和model中的数据会被放入到request请求中
        map.put("user","zjb");
        map.put("job","java程序员");
        model.addAttribute("sal",3000);
        //把cookie信息写入到浏览器中
        Cookie email = new Cookie("email", "zjb@souhu.com");
        response.addCookie(email);
        return "forward:/registerOk";
    }
    @RequestMapping("/registerOk")
    @ResponseBody
    public String registerOk(HttpServletRequest request){
        System.out.println("user--"+request.getAttribute("user"));
        System.out.println("job--"+request.getAttribute("job"));
        System.out.println("sal--"+request.getAttribute("sal"));
        return "success";
    }
}
